import serial
import signal
import re
import os
import time
import setproctitle
import _thread as thread

# plug spec:
# https://home.miot-spec.com/spec/cuco.plug.v3

plugCurrPower = '-1'
plugStateHis = False

def timeStr():
    return time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))

def exit(signum, frame):
    ser.close()
    print('\n', timeStr(), 'stopping...\n')
    exit(0)

def configPlug(isPwrOn):
    # in cli:
    # miiocli device --ip 192.168.3.5 --token 21f7d80a678cf92131d879b37d1e78f3  raw_command set_properties "[{'did':'575499557','value':True,'siid':2,'piid':1}]"
    global plugStateHis
    if (plugStateHis == isPwrOn):
        return
    print(timeStr(), 'switch changing from ' + str(plugStateHis) + ' to ' + str(isPwrOn))
    plugStateHis = isPwrOn
    if (isPwrOn):
        os.system("miiocli device --ip 192.168.3.5 --token 21f7d80a678cf92131d879b37d1e78f3  raw_command set_properties \"[{'did':'575499557','value':True,'siid':2,'piid':1}]\"")
    else:
        os.system("miiocli device --ip 192.168.3.5 --token 21f7d80a678cf92131d879b37d1e78f3  raw_command set_properties \"[{'did':'575499557','value':False,'siid':2,'piid':1}]\"")

def readPlugPower(title, token):
    # in cli:
    # miiocli device --ip 192.168.3.5 --token 21f7d80a678cf92131d879b37d1e78f3  raw_command get_properties "[{'did':'575499557','siid':11,'piid':2}]"
    # [{'did': '575499557', 'siid': 11, 'piid': 2, 'code': 0, 'value': 92}]
    print('hello ' + title)
    global plugCurrPower
    while(True):
        process = os.popen("miiocli device --ip 192.168.3.5 --token 21f7d80a678cf92131d879b37d1e78f3  raw_command get_properties \"[{'did':'575499557','siid':11,'piid':2}]\"")
        ret = process.read()
        ret = ret.replace(' ', '')
        ret = re.findall(r"\d+\.?\d*", ret)
        if (len(ret) != 5):
            return ''
        plugCurrPower = ret[4]
        time.sleep(0.5)

def SendCmd(ser, cmd):
    ser.write(cmd.encode())
    ser.write(b'\x0d\x1b[15;1R\x1b[15;233R\x1b[15;1R\x1b[15;9R')
    time.sleep(0.3)
    ret = ser.read_all()
    return ret.decode("utf-8")

SERIAL_NAME = '/dev/ttyUSB0'

signal.signal(signal.SIGINT, exit)
signal.signal(signal.SIGTERM, exit)

procTitle = "PerMonMst"
setproctitle.setproctitle(procTitle)
print(timeStr(), "hello ", procTitle)

ser = serial.Serial(SERIAL_NAME, 115200, timeout=1)
thread.start_new_thread(readPlugPower, ('threadReadPlugPower', 0))
# 脚本启时同步一次开关内存值
ret = SendCmd(ser, 'echo ' + 'hello,' + procTitle)
plugStateHis = (ret.find('PlugPwrOn') != -1)

while (1):
    if (ser.isOpen() == False):
        print(timeStr(),"SERIAL_NAME closed")
        exit(1)
    time.sleep(0.3)
    ret = SendCmd(ser, 'echo plugPower=' + plugCurrPower)
    # print(ret)
    if (ret.find('PlugPwrOff') != -1):
        configPlug(False)
    if (ret.find('PlugPwrOn') != -1):
        configPlug(True)